package models

import (
	//"fmt"
	"pro_server/utils"
	"time"
    "fmt"
	"gorm.io/gorm"
)

type UserBasic struct {
	Id         int       `json:"Id"`
	Name       string    `json:"Name"`
	PassWord   string    `json:"Password"`
	Email      string    `json:"Email"`
	Identity   string    `json:"Identity"`	//身份令牌
	DeviceInfo string    `json:"DeviceInfo"`    //设备信息
	Avatar     string    `json:"Avatar"`    //头像
	Created_at time.Time `json:"Created_at"` //创建时间
	Updated_at time.Time `json:"Updated_at"` //更新时间
}

type ClientUser struct {
	Id         int       `json:"Id"`
	Name       string    `json:"Name"`
	Email      string    `json:"Email"`
	Identity   string    `json:"Identity"`	//身份令牌
	Avatar     string    `json:"Avatar"`    //头像图片名字，当图片加载出错时，用于向服务器请求再次加载
   // Picture    string                       //储存base64编码后的图片
    FriendList []FriendUser
}
  
type FriendUser struct {
	Id         int       
	Name       string    
	Email      string    
	Identity   string   
	Avatar     string    
}


func (table *UserBasic) TableName() string {
	return "user_basic"
}

func FindUserById(id int) UserBasic {
	user := UserBasic{}
	utils.DB.Where("id = ?", id).First(&user)
	return user
}

func FindUserByEmail(email string) *gorm.DB {
	user := UserBasic{}
	return utils.DB.Where("email = ?", email).First(&user)
}

//获取好友列表
func GetFriendList(id int) ([]FriendUser, error) {
    
	var results []FriendUser
    err := utils.DB.Table("user_basic").
        Select("user_basic.id, user_basic.name, user_basic.email, user_basic.avatar, user_basic.created_at").
        Joins("INNER JOIN contact ON contact.friend_id = user_basic.id").
        Where("contact.id =?", id).
        Scan(&results).Error
    return results, err
}

func CreateUser(user UserBasic) *gorm.DB {
	return utils.DB.Create(&user)
}

func DeleteUser(user UserBasic) *gorm.DB {
	return utils.DB.Delete(&user)
}

func GetUserData(id int) UserBasic {
    user := UserBasic{}
	utils.DB.Where("id = ?", id).First(&user)

	//token加密
	str := fmt.Sprintf("%d", time.Now().Unix())
	temp := utils.MD5Encode(str)
	updates := map[string]interface{}{
		"identity": temp,
		"updated_at":  time.Now(),
	}
	utils.DB.Model(&user).Where("id = ?", user.Id).Updates(updates)
	return user
}
// func UpdateUser(user UserBasic) *gorm.DB {
// 	return utils.DB.Model(&user).Updates(UserBasic{Name: user.Name, PassWord: user.PassWord, Phone: user.Phone, Email: user.Email, Avatar: user.Avatar})
// }
